/*
 * Copyrignt (c) xuzeshui.com. All Rights Reserved.
 * Author: Zeshui Xu<i@xuzeshui.com>
 * Created Time: 2016-10-12 16:37:27
 * Last Modified: 2016-10-13 10:34:08
 * File Name: controllers/mobilechange.go
 * Description:
 */
package controllers

import (
	"encoding/json"

	"passport/account"
	"passport/errorcode"
	"passport/user"

	log "github.com/cihub/seelog"
)

type MobileChangeController struct {
	LoginedController
}

func (p *MobileChangeController) MobileChange() {
	defer p.Output("MobileChange")
	body := p.Ctx.Input.RequestBody
	log.Debugf("recv body: %s", string(body))
	var req struct {
		MobileNew string `json:"mobile_new"`
	}
	if err := json.Unmarshal(body, &req); err != nil {
		p.Resp["code"] = errorcode.EC_GL_INVALID_JSON_BODY
		p.Resp["msg"] = errorcode.Msg(errorcode.EC_GL_INVALID_JSON_BODY)
		return
	}

	if req.MobileNew == "" {
		p.Resp["code"] = errorcode.EC_GL_INTERNAL_ERROR
		p.Resp["msg"] = "新手机号不能为空"
		return
	}

	ui, uiErr := user.GetUserService().GetAllUserInfo(p.UserId)
	if uiErr != nil {
		p.Resp["code"] = errorcode.EC_GL_INTERNAL_ERROR
		p.Resp["msg"] = "查询用户信息失败"
		return
	}
	if ui == nil || ui.Mobile == "" {
		p.Resp["code"] = errorcode.EC_GL_INTERNAL_ERROR
		p.Resp["msg"] = "用户信息不存在或者未绑定过手机"
		return
	}

	aiOld, aiErr := account.GetAccountService().GetAllAccountInfo(account.ACCOUNT_TYPE_MOBILE, ui.Mobile)
	if aiErr != nil {
		p.Resp["code"] = errorcode.EC_GL_INTERNAL_ERROR
		p.Resp["msg"] = "查询旧账号错误"
		return
	}
	if aiOld == nil {
		p.Resp["code"] = errorcode.EC_GL_INTERNAL_ERROR
		p.Resp["msg"] = "查询旧账号失败"
		return
	}

	if aiNew, err := account.GetAccountService().GetAllAccountInfo(account.ACCOUNT_TYPE_MOBILE, req.MobileNew); err != nil {
		p.Resp["code"] = errorcode.EC_GL_INTERNAL_ERROR
		p.Resp["msg"] = "查询新账号错误"
		return
	} else if aiNew != nil {
		p.Resp["code"] = errorcode.EC_MOBILE_CHANGE_CONFLICT
		p.Resp["msg"] = "更换的手机号已注册过"
		return
	}

	//老手机账号解绑
	account.GetAccountBindService().RecordUserAccountUnbind(p.UserId, account.ACCOUNT_TYPE_MOBILE)
	aichanger := account.NewAccountInfoChanger(ui.Mobile, account.ACCOUNT_TYPE_MOBILE)
	aichanger.Delete()

	//新手机账号绑定
	bindinfoReq := &account.AccountBindInfoReq{
		ExtFrom: account.ACCOUNT_TYPE_MOBILE,
		ExtId:   req.MobileNew,
	}
	bindStatus, msg := account.GetAccountBindService().AccountBind(p.UserId, false, bindinfoReq)
	if bindStatus == errorcode.EC_GL_SUCCESS {
		uinfochanger := user.NewUserInfoChanger(p.UserId)
		uinfochanger.SetMobile(req.MobileNew)
		uinfochanger.Save()
	}
	p.Resp["code"] = bindStatus
	p.Resp["msg"] = msg
}
